package com.wss.common.widget;

import butterknife.BindComponent;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.wss.common.base.BaseApplication;
import com.wss.common.base.ResourceTable;
import com.wss.common.utils.*;
import com.wss.common.widget.attrs.StyleCountClickView;
import com.wss.common.widget.dialog.AppDialog;
import com.wss.common.widget.dialog.DialogType;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * Describe：加减Viw，最大支持10000，最小支持 0
 * Created by 吴天强 on 2018年9月27日18:13:09
 */
public class CountClickView extends DirectionalLayout implements Component.ClickedListener {

    public static final int MIN_COUNT = 0;
    public static final int INIT_COUNT = 1;
    public static final int MAX_COUNT = 10000;

    Text tvCount;

    Image ivPlus;

    Image ivMinus;

    /**
     * 减 控件父类
     */
    DirectionalLayout llMinus;
    /**
     * 加 控件父类
     */
    DirectionalLayout llPlus;

    private int maxCount = MAX_COUNT;
    private int minCount = MIN_COUNT;
    private int currentCount = INIT_COUNT;
    private int textColor = Color.BLACK.getValue();
    private int textSize = 14;

    /**
     * 是否支持如输入 默认不支持
     */
    private boolean input = false;

    private OnClickAfterListener afterClickListener = null;

    public CountClickView(Context context) {
        this(context, null);
    }

    public CountClickView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public CountClickView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);

        maxCount = attrSet.getAttr(StyleCountClickView.ccvMax).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvMax).get().getIntegerValue() : maxCount;
        minCount = attrSet.getAttr(StyleCountClickView.ccvMin).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvMin).get().getIntegerValue() : minCount;
        currentCount = attrSet.getAttr(StyleCountClickView.ccvCurrent).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvCurrent).get().getIntegerValue() : currentCount;
        input = attrSet.getAttr(StyleCountClickView.ccvInput).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvInput).get().getBoolValue() : input;
        textColor = attrSet.getAttr(StyleCountClickView.ccvTextColor).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvTextColor).get().getColorValue().getValue() : textColor;
        textSize = attrSet.getAttr(StyleCountClickView.ccvTextSize).isPresent() ?
                attrSet.getAttr(StyleCountClickView.ccvTextSize).get().getIntegerValue() : textSize;

        init();
    }

    private void init() {

        Component rootComponent = LayoutScatter
                .getInstance(getContext())
                .parse(ResourceTable.Layout_layout_count_click_view, this, false);
        addComponent(rootComponent);

        tvCount = (Text) findComponentById(ResourceTable.Id_tv_count);
        ivPlus = (Image) findComponentById(ResourceTable.Id_iv_plus);
        ivMinus = (Image) findComponentById(ResourceTable.Id_iv_minus);
        llMinus = (DirectionalLayout) findComponentById(ResourceTable.Id_ll_minus);
        llPlus = (DirectionalLayout) findComponentById(ResourceTable.Id_ll_plus);

        llMinus.setClickedListener(this::onClick);
        llPlus.setClickedListener(this::onClick);
        tvCount.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                onCountClick();
            }
        });

        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(Color.TRANSPARENT.getValue()));
        setBackground(element);
        setTextColor(textColor);
        setTextSize(textSize);
        setCurrCount(currentCount);
        judgeTheViews(getCount());
    }

//    @OnClick({ResourceTable.Id_ll_minus, ResourceTable.Id_ll_plus})
    public void onClick(@NotNull Component v) {
        int count = getCount();
        if (ResourceTable.Id_ll_plus == v.getId()) {
            if (count < getMaxCount()) {
                tvCount.setText(String.valueOf(++count));
            }
        } else if (ResourceTable.Id_ll_minus == v.getId()) {
            if (count > getMinCount()) {
                tvCount.setText(String.valueOf(--count));
            }
        } else if (ResourceTable.Id_tv_count == v.getId()) {
        }
        judgeTheViews(count);
        if (afterClickListener != null) {
            afterClickListener.onAfter(this, getCount());
        }
    }

//    @OnClick({ResourceTable.Id_tv_count})
    public void onCountClick() {
        if (input) {
            new AppDialog.Builder(getContext())
                    .setDialogType(DialogType.INPUT)
                    .setInputType(InputAttribute.PATTERN_NUMBER)
                    .setInputDefaultText(String.valueOf(getCount()))
                    .setTitle("输入数量")
                    .setRightButton(getContext().getString(ResourceTable.String_confirm), val -> {
                        if (Utils.isNumber(val)) {
                            int count = Integer.parseInt(val);
                            if (count > MAX_COUNT) {
                                count = maxCount;
                                ToastUtils.show("超过了设置的最大值");
                            } else if (count < MIN_COUNT) {
                                count = MIN_COUNT;
                                ToastUtils.show("超过了设置的最小值");
                            }
                            setCurrCount(count);
                        }
                    })
                    .create()
                    .show();
        }
    }

    /**
     * 根据加减 设置显示的控件View
     *
     * @param count 数量
     */
    private void judgeTheViews(int count) {
        ivMinus.setEnabled(count > getMinCount());
        ivPlus.setEnabled(count < getMaxCount());
    }

    /**
     * 判断最大值
     *
     * @return 返回最大值
     */
    @Contract(pure = true)
    private int getMaxCount() {
        return Math.min(maxCount, MAX_COUNT);
    }

    /**
     * 判断最小值
     *
     * @return 返回最小值
     */
    @Contract(pure = true)
    private int getMinCount() {
        return Math.max(minCount, MIN_COUNT);
    }

    /**
     * 设置监听
     *
     * @param afterClickListener l
     */
    public void setAfterClickListener(OnClickAfterListener afterClickListener) {
        this.afterClickListener = afterClickListener;
    }

    /**
     * 设置是否支出输入  默认不支持
     *
     * @param input 输入
     */
    public void setInput(boolean input) {
        this.input = input;
    }

    /**
     * 设置文字颜色
     *
     * @param textColor 颜色
     */
    public void setTextColor(int textColor) {
        this.textColor = textColor;
        tvCount.setTextColor(new Color(textColor));
    }

    /**
     * 设置文字大小
     *
     * @param textSize 大小
     */
    public void setTextSize(int textSize) {
        this.textSize = textSize;
        tvCount.setTextSize(PxUtils.fp2px(this.textSize));
    }

    /**
     * 设置默认显示的数量
     *
     * @param count 数量
     */
    public void setCurrCount(int count) {
        tvCount.setText(String.valueOf(count));
        judgeTheViews(count);
    }

    /**
     * 设置最大值
     *
     * @param maxCount 最大值
     */
    public void setMaxCount(int maxCount) {
        if (maxCount < getMinCount()) {
            maxCount = INIT_COUNT;
        }
        this.maxCount = maxCount;
        judgeTheViews(getCount());
    }

    /**
     * 设置最小值
     *
     * @param minCount 最小值
     */
    public void setMinCount(int minCount) {
        if (minCount > getMaxCount()) {
            minCount = INIT_COUNT;
        }
        this.minCount = minCount;
        judgeTheViews(getCount());
    }


    /**
     * 返回操作后的数量
     *
     * @return 数量
     */
    public int getCount() {
        String text = tvCount.getText().toString().trim();
        if (TextUtils.isEmpty(text)) {
            return INIT_COUNT;
        }
        return Integer.parseInt(text);
    }

    /**
     * 设置 按钮父类的大小
     */
    public void setBtnParentSize(int width, int height) {
        llMinus.setLayoutConfig(new DirectionalLayout.LayoutConfig(PxUtils.vp2px(width), PxUtils.vp2px(height)));
        llPlus.setLayoutConfig(new DirectionalLayout.LayoutConfig(PxUtils.vp2px(width), PxUtils.vp2px(height)));
        //如果设置了该处大小 则需要更新中间View的高度
        DirectionalLayout.LayoutConfig layoutParams = (LayoutConfig) tvCount.getLayoutConfig();
        layoutParams.height = PxUtils.vp2px(height);
    }

    /**
     * 设置 按钮父类背景
     */
    public void setBtnParentBg(int bgColor) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(ColorUtils.colorToRgbColor(getContext().getColor(bgColor)));
        llMinus.setBackground(element);
        llPlus.setBackground(element);
    }


    /**
     * 设置加减按钮大小
     */
    public void setBtnSize(int width, int height) {
        ivPlus.setLayoutConfig(new DirectionalLayout.LayoutConfig(PxUtils.vp2px(width),
                PxUtils.vp2px(height)));
        ivMinus.setLayoutConfig(new DirectionalLayout.LayoutConfig(PxUtils.vp2px(width),
                PxUtils.vp2px(height)));
    }

    /**
     * 设置加减控件的资源文件
     */
    public void setButtonRes(int addDrawableNormal,
                             int addDrawableDisable,
                             int minusDrawableNormal,
                             int minusDrawableDisable) {

        try {
            PixelMapElement addDrawableElement = new PixelMapElement(getContext()
                    .getResourceManager().getResource(addDrawableNormal));
            PixelMapElement minusDrawableElement = new PixelMapElement(getContext()
                    .getResourceManager().getResource(minusDrawableNormal));
            PixelMapElement addDrawableDisableElement = new PixelMapElement(getContext()
                    .getResourceManager().getResource(addDrawableDisable));
            PixelMapElement minusDrawableDisableElement = new PixelMapElement(getContext()
                    .getResourceManager().getResource(minusDrawableDisable));
            ivPlus.setBackground(addDrawableElement);
            ivMinus.setBackground(minusDrawableElement);

            ivPlus.setComponentStateChangedListener(new ComponentStateChangedListener() {
                @Override
                public void onComponentStateChanged(Component component, int i) {
                    if (ComponentState.isStateMatched(ComponentState.COMPONENT_STATE_DISABLED, i)) {
                        ivPlus.setBackground(addDrawableDisableElement);
                    } else {
                        ivPlus.setBackground(addDrawableElement);
                    }
                }
            });

            ivMinus.setComponentStateChangedListener(new ComponentStateChangedListener() {
                @Override
                public void onComponentStateChanged(Component component, int i) {
                    if (ComponentState.isStateMatched(ComponentState.COMPONENT_STATE_DISABLED, i)) {
                        ivMinus.setBackground(minusDrawableDisableElement);
                    } else {
                        ivMinus.setBackground(minusDrawableElement);
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
    }

    /***
     * 设置中间View一些属性
     * @param bgColor 背景色
     * @param textColor 字体颜色  使用默认颜色 给0 即可
     * @param marginLeft marginLeft
     * @param marginRight marginRight
     */
    public void setCountViewAttr(int bgColor, int textColor, int marginLeft, int marginRight) {
        DirectionalLayout.LayoutConfig layoutParams = (LayoutConfig) tvCount.getLayoutConfig();
        layoutParams.setMargins(PxUtils.vp2px(marginLeft), 0, PxUtils.vp2px(marginRight), 0);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(ColorUtils.colorToRgbColor(getContext().getColor(bgColor)));
        tvCount.setBackground(element);
        if (textColor != 0) {
            tvCount.setTextColor(new Color(textColor));
        }
    }

    /**
     * 操作之后监听回调
     */
    public interface OnClickAfterListener {

        /**
         * 操作之后
         *
         * @param view  CountClickView
         * @param value 值
         */
        void onAfter(CountClickView view, int value);
    }
}
